package com.smallkingson.ylib.view.adapter;

import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import org.apache.http.protocol.ImmutableHttpProcessor;

public abstract class YRecyclerAdapter extends RecyclerView.Adapter<YRecyclerAdapter.YViewHolder> {

    private YViewHolder tempHolder;

    @Override
    public YViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = getView();
        if (view == null) {
            view = LayoutInflater.from(
                    parent.getContext()).inflate(getLayoutRes(), parent,
                    false);
        }
        if (view == null) {
            throw new IllegalArgumentException("must implements getView() or getLayoutRes()");
        }
        YViewHolder holder = new YViewHolder(view);
        return holder;
    }

    protected int getLayoutRes() {
        return -1;
    }

    protected View getView() {
        return null;
    }

    @Override
    public void onBindViewHolder(YViewHolder holder, int position) {
        tempHolder = holder;
        setupView(holder, position);
    }

    protected abstract void setupView(YViewHolder holder, int position);

    public Button $btn(int id) {

        Button button = (Button) tempHolder.$(id);

        return button;
    }

    public ViewGroup $vp(int id) {
        ViewGroup viewGroup = (ViewGroup) tempHolder.$(id);
        return viewGroup;
    }

    public TextView $text(int id) {
        TextView text = (TextView) tempHolder.$(id);
        return text;
    }

    public CheckBox $checkBox(int id) {
        CheckBox cb = (CheckBox) tempHolder.$(id);
        return cb;
    }

    public ImageView $img(int id) {

        ImageView img = (ImageView) tempHolder.$(id);

        return img;
    }

    public View $view(int id) {
        return tempHolder.$(id);
    }

    public class YViewHolder extends RecyclerView.ViewHolder {
        private SparseArray<View> holder;

        public YViewHolder(View itemView) {
            super(itemView);
            holder = new SparseArray<>();
        }

        public View $(int id) {
            View view = holder.get(id, null);
            if (view == null) {
                view = itemView.findViewById(id);
                holder.put(id, view);
            }
            return view;
        }
    }
}
